<template>
    <StElUpload
            v-bind="$attrs"
            ref="stelupload"
            :multiple="false"
            :auto-upload="$attrs.autoUpload === false ? false : true"
            :show-file-list="$attrs.showFileList === false ? false : true"
            :file-list="fileList"
            :on-change="onChange">
      <template v-if="triggerType == 'drag'">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </template>
      <template v-else-if="triggerType == 'button'">
        <el-button size="small" type="primary">点击上传</el-button>
      </template>
      <template v-else-if="triggerType == 'card'">
        <i class="el-icon-plus"></i>
      </template>
        <div v-if="$attrs.tips" class="el-upload__tip" slot="tip" v-html="$attrs.tips"></div>
    </StElUpload>
</template>

<script>
    export default {
        name: 'StElUploadFile',
        props:{
            value: null,
            // 触发类型
            triggerType: null
        },
        data() {
            return {
              hasInit: false,
              fileList: []
            };
        },
        methods: {
            onChange (file, fileList) {
              this.hasInit = true
              let r = []
              fileList.forEach(item => {
                if(item.status == 'success'){
                  if(item.response){
                    r.push(item.response.url)
                  }else {
                    r.push(item.url)
                  }
                }
              })
                this.$emit('input',r)
            },
        },
        watch:{
            value(val) {
                if (!val) {
                    this.$refs.stelupload.getUploadRef().clearFiles()
                }else {
                  if(!this.hasInit){
                    let temp = []
                    val.forEach(item => {
                      temp.push({
                        name: item,
                        url: item
                      })
                    })
                    this.fileList = temp
                  }
                }
            }
        }
    }
</script>
